package com.sunflower.uploader.controller;

import java.io.File;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value="webuploader")
public class WebUploaderContoller {
	@RequestMapping(value = "/fileupload", method = { RequestMethod.GET })
	public String fileupload(ModelMap map, HttpServletRequest request,HttpServletResponse response) {
		return "test";
	}
	
	@ResponseBody
	@RequestMapping(value = "/dofileupload", method = { RequestMethod.POST })
	public String dofileupload(MultipartFile file,ModelMap map, HttpServletRequest request,HttpServletResponse response) {
		System.out.println("开始");  
        String path = request.getSession().getServletContext().getRealPath("upload");  
        String fileName = file.getOriginalFilename();  
//        String fileName = new Date().getTime()+".jpg";  
        System.out.println(path);  
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        map.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);  
        map.addAttribute("uploadSuccess", true); 
        StringBuffer rsw = new StringBuffer();
        for(Entry<String,Object> s:map.entrySet()){
        	rsw.append("\""+s.getKey()+"\":");
        	rsw.append("\""+s.getValue()+"\",");
        }
        return rsw.substring(0, rsw.length()-1);  
    }  
}
